from rest_framework import mixins
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet

from areas import serializers

from areas.models import Area
from rest_framework_extensions.cache.mixins import CacheResponseMixin


class AreaInfoView(mixins.DestroyModelMixin,CacheResponseMixin,ReadOnlyModelViewSet):
    # serializer_class = serializers.AreaInfoSerializer
    # queryset = Area.objects.filter(parent=None)
    def get_serializer_class(self):
        if self.action == "list":
            return serializers.AreaInfoSerializer
        else:
            return serializers.AreaSubsInfoSerializer

    def get_queryset(self):
        if self.action == "list":
            return Area.objects.filter(parent=None)
        else:
            return Area.objects.all()

    # 3,修改地址的标题
    @action(methods=["put"], detail=True)
    def title(self, request, pk):
        # 1,获取参数
        dict_data = request.data
        address = self.get_object()

        # 2,创建序列化器
        serializer = serializers.AddressTitleSerializer(instance=address, data=dict_data)

        # 3,校验数据,入库
        serializer.is_valid(raise_exception=True)
        serializer.save()

        # 4,返回
        return Response(serializer.data)

    # 4,重写destory方法,为了逻辑删除
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.is_deleted = True
        instance.save()
        return Response(status=status.HTTP_204_NO_CONTENT)
